package com.sellerSystem.controller;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sellerSystem.service.SellerManager;
import com.sellerSystem.vo.Commodity;
import com.sellerSystem.vo.ComplaintInfo;
import com.sellerSystem.vo.Demo;
import com.sellerSystem.vo.OrderForm;
import com.sellerSystem.vo.Seller;
import com.sellerSystem.vo.SellerAddress;
import com.sellerSystem.vo.Temp;

@Controller
public class SellerManagerController {
	@Autowired(required = true)
	private SellerManager sm;

	@RequestMapping("login")
	public String login(String sellerTel, String sellerPsd,
			HttpServletRequest request) {
		Seller seller = sm.login(sellerTel, sellerPsd);
		if (seller != null) {
			//MyListenerQueue();
			request.getSession().setAttribute("seller", seller);
			int s = seller.getSellerState();
			if (s == 0) {
				return "approvaling";
			} else if (s == 2) {
				return "unapproval";
			} else if (s == 3) {
				return "blackbill";
			} else
				return "loginSuc";

		} else {
			return "fail";
		}

	}

	@RequestMapping("regist")
	public String regist(Seller seller, SellerAddress sa, String sellerTel,
			HttpServletRequest request) {
		seller.setSellerAddress(sa);
		if (sm.isExist(sellerTel) == false) {
			int rs = sm.regist(seller);
			// request.getSession().setAttribute("", arg1);
			if (rs != 0)
				return "registSuc";
			else
				return "regist";
		} else {
			return "registFail";
		}
	}

	@RequestMapping(value="/findseller")
	@ResponseBody
	public ArrayList<Seller> findSeller(Integer sellerState,
			HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		ArrayList<Seller> ls = sm.seller(sellerState);
		return ls;
	}

	@RequestMapping("loginSuc")
	@ResponseBody
	public ArrayList<Commodity> shopping(HttpServletRequest request) {
		
		HttpSession session = request.getSession();
		Seller seller_session = (Seller) session.getAttribute("seller");
		String sellerName = seller_session.getSellerName();

		if (sellerName != null) {
			ArrayList<Commodity> lc = sm.findCommodity(sellerName);
			request.getSession().setAttribute("lc", lc);
			// List<Commodity> commoditylist = new ArrayList<Commodity>();
			// commoditylist.add(commodity);
			return lc;
		}
		return null;

	}

	@RequestMapping("addCommodity")
	public String addCommodity(Commodity commodity, HttpServletRequest request) {
		sm.addCommodity(commodity);
		return "addSuc";
	}

	@RequestMapping(value="/findsellerbyid")
	@ResponseBody
	public Seller finSellerById(Integer sellerId,HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		Seller s = sm.findId(sellerId);
		System.out.println(s.toString());
		return s;
	}

	@RequestMapping("modifyinfo")
	public String modifyInfo(Seller seller, SellerAddress sa,
			HttpServletRequest request) {
		seller.setSellerAddress(sa);
		sm.modifyInfo(seller);
		return "info";
	}

	@RequestMapping("modifycommodity")
	public void modifyCommodity(Commodity commodity, HttpServletRequest request) {
		System.out.println(commodity.getCommodityName());
		System.out.println(commodity.toString());
		sm.modifyCommodity(commodity);
	}

	@RequestMapping("deletecommodity")
	public void deleteCommodity(Commodity commodity, HttpServletRequest request) {
		System.out.println("@@@" + commodity);
		sm.deleteCommodity(commodity);
	}

	@RequestMapping(value="/modifystate")
	@ResponseBody
	public String modifyState(Integer sellerId, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		sm.modifystate(sellerId);
		System.out.println("正在修改state+++++++++++++++");
		return "state修改完成";
	}

	@RequestMapping(value="/modifyorderform")
	public void modifyofState(OrderForm orderForm, HttpServletResponse response) {
		System.out.println("准备修改");
		response.setContentType("application/json;charset=UTF-8");
		sm.modifyofstate(orderForm);

		System.out.println("正在修改state+++++++++++++++");
	}

	@RequestMapping(value="/approvalfail",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String approvalfail(Integer sellerId, String approvalOpinion,
			HttpServletResponse response) {
		//response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		String  string = null;
		try {
			string = new String(approvalOpinion.getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(string);
		sm.approvalfail(sellerId, string);
		System.out.println("正在修改state+++++++++++++++");
		return "state修改完成";
	}

	@RequestMapping(value="/allbill")
	@ResponseBody
	public List<OrderForm> allbill( HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		List<OrderForm> lo = sm.allbill();
		return lo;
	}

	@RequestMapping(value="/joinblacklist")
	@ResponseBody
	public String joinblack(Integer sellerId, String sellerRemark,
			HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		String  string = null;
		try {
			string = new String(sellerRemark.getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sm.joinblack(sellerId, string);
		return "joinblacklist";
	}

	@RequestMapping(value="/ifblacklist")
	@ResponseBody
	public List<Seller> ifBlacklist( HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		List<Seller> ls = sm.ifBlacklist();
		return ls;
	}

	@RequestMapping("billbyid")
	@ResponseBody
	public List<OrderForm> billbyid(String sellerName, String time1,
			String time2) {
		List<OrderForm> lo = sm.billbyid(sellerName, time1, time2);
		return lo;
	}

	@RequestMapping(value="/orderformbyname")
	@ResponseBody
	public List<OrderForm> billbyname(String sellerName,
			HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		List<OrderForm> lo = sm.billName(sellerName);
		// System.out.println(".............."+ lo.get(0).toString());
		return lo;
	}

	@RequestMapping(value="/orderform")
	@ResponseBody
	public List<Demo> singlebill(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		Seller seller_session = (Seller) session.getAttribute("seller");
		String sellerName = seller_session.getSellerName();
		response.setContentType("application/json;charset=UTF-8");
		List<Demo> lo = sm.billName1(sellerName);
		// System.out.println(".............."+ lo.get(0).toString());
		System.out.println(lo.get(0).getOrderStatus());
		return lo;
	}
/*	@RequestMapping(value="/orderform")
	@ResponseBody
	public List<OrderForm> singlebill(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		Seller seller_session = (Seller) session.getAttribute("seller");
		String sellerName = seller_session.getSellerName();
		response.setContentType("application/json;charset=UTF-8");
		List<OrderForm> lo = sm.billName(sellerName);
		// System.out.println(".............."+ lo.get(0).toString());
		System.out.println(lo.get(0).getOrderStatus());
		return lo;
	}
*/
	@RequestMapping(value="/noblacklist")
	@ResponseBody
	public String noblack(Integer sellerId, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		sm.noblack(sellerId);
		return "success";
	}

	@RequestMapping(value="/complaintinfo")
	@ResponseBody
	public List<ComplaintInfo> complaininfo( HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		List<ComplaintInfo> lc = sm.complaintInfo();
		return lc;
	}

	@RequestMapping(value="/handlecomplaint")
	@ResponseBody
	public String handlecomplaint(Integer complaintInfoId,Integer complaintStatu,String complaintFeedback, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		String  string = null;
		try {
			string = new String(complaintFeedback.getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sm.handlecomplaint(complaintInfoId,complaintStatu,string);
		return "success";
	}

	@RequestMapping(value="/billbyid_day")
	@ResponseBody
	public List<Temp> findBillBySellerIdAndDay(String sellerName, HttpServletResponse response) {
		// TODO Auto-generated method stub
		response.setContentType("application/json;charset=UTF-8");
		return sm.findBillBySellerIdAndDay(sellerName);
	}

	@RequestMapping(value="/billbyid_month")
	@ResponseBody
	public List<Temp> findBillBySellerIdAndMonth(String sellerName, HttpServletResponse response) {
		// TODO Auto-generated method stub
		response.setContentType("application/json;charset=UTF-8");
		return sm.findBillBySellerIdAndMonth(sellerName);
	}

	@RequestMapping(value="/billbyid_year")
	@ResponseBody
	public List<Temp> findBillBySellerIdAndYear(String sellerName, HttpServletResponse response) {
		// TODO Auto-generated method stub
		response.setContentType("application/json;charset=UTF-8");
		return sm.findBillBySellerIdAndYear(sellerName);
	}

	@RequestMapping(value="/billbyday")
	@ResponseBody
	public List<Temp> findBillByDay( HttpServletResponse response) {
		// TODO Auto-generated method stub
		response.setContentType("application/json;charset=UTF-8");
		return sm.findBillByDay();
	}

	@RequestMapping(value="/billbymonth")
	@ResponseBody
	public List<Temp> findBillByMonth( HttpServletResponse response) {
		// TODO Auto-generated method stub
		response.setContentType("application/json;charset=UTF-8");
		return sm.findBillByMonth();
	}

	@RequestMapping(value="/billbyyear")
	@ResponseBody
	public List<Temp> findBillByYear( HttpServletResponse response) {
		// TODO Auto-generated method stub
		response.setContentType("application/json;charset=UTF-8");
		return sm.findBillByYear();
	}

	
	
	
	public static void MyListenerQueue() {

		System.out.println("=====================================================================================");
		Timer timer = new Timer(true);
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				/**
				 * 监听新申请
				 */
				ConnectionFactory factory = new ActiveMQConnectionFactory(
						"tcp://127.0.0.1:61616");
				Destination queue1 = new ActiveMQQueue("seller");
				try {
					Connection con = factory.createConnection();
					con.start();
					// System.out.println(con);
					Session sen = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
					MessageConsumer consumer = sen.createConsumer(queue1);
					consumer.setMessageListener(new MessageListener() {

						@Override
						public void onMessage(Message message) {
							TextMessage msg = (TextMessage) message;
							JSONObject jso = null;
							String recMessage = null;
							Integer sellerId = 0;
							Integer sellerState = 0;
							String approvalOpinion = null;
							String sellerRemark = null;
							String sellerName = null;
							Integer complaintInfoId = 0;
							Integer complaintStatu = 0;
							String complaintFeedback = null;
							try {
								jso = new JSONObject(msg.getText());
								recMessage = jso.get("query").toString();
								System.out.println(recMessage);
								String url = null;
								Destination queue = new ActiveMQQueue("backstage");
								MessageProducer producer = sen.createProducer(queue);
								String ip = InetAddress.getLocalHost().getHostAddress();
								if (recMessage.equals("all")) {
									System.out.println("all............................");
									sellerState = jso.getInt("sellerState");
									url = ("http://" + ip
											+ ":8080/sellerSystem/findseller?sellerState=" + sellerState);
									System.out.println(url);
								} else if (recMessage.equals("modifystatebyid")) {
									sellerId = jso.getInt("sellerId");
									sellerState = jso.getInt("sellerState");
									System.out.println("modifystatebyid..................");
									url = ("http://" + ip
											+ ":8080/sellerSystem/modifystate?sellerId=" + sellerId);
									System.out.println(url);
								} else if (recMessage.equals("querybyid")) {
									sellerId = jso.getInt("sellerId");
									System.out
											.println("querybyid............................");
									url = ("http://" + ip
											+ ":8080/sellerSystem/findsellerbyid?sellerId=" + sellerId);
									System.out.println(url);
								} else if (recMessage.equals("allbill")) {
									System.out
											.println("allbill............................");
									url = ("http://" + ip + ":8080/sellerSystem/allbill");
									System.out.println(url);
								} else if (recMessage.equals("billbyid")) {
									System.out
											.println("billbyid............................");
									sellerId = jso.getInt("sellerId");
									url = ("http://" + ip
											+ ":8080/sellerSystem/billbyid?sellerId=" + sellerId);
									System.out.println(url);
								} else if (recMessage.equals("joinblacklist")) {
									sellerId = jso.getInt("sellerId");
									sellerRemark = jso.getString("sellerRemark");
									System.out
											.println("joinblacklist.................................");
									url = ("http://" + ip
											+ ":8080/sellerSystem/joinblacklist?sellerId="
											+ sellerId + "&sellerRemark=" + sellerRemark);
									System.out.println(url);
								} else if (recMessage.equals("ifblacklist")) {
									System.out
											.println("ifBlacklist.................................");
									url = ("http://" + ip + ":8080/sellerSystem/ifblacklist");
								} else if (recMessage.equals("noblacklist")) {
									sellerId = jso.getInt("sellerId");
									System.out.println("noblacklist..................");
									url = ("http://" + ip
											+ ":8080/sellerSystem/noblacklist?sellerId=" + sellerId);
									System.out.println(url);
								} else if (recMessage.equals("approvalfail")) {
									sellerId = jso.getInt("sellerId");
									sellerState = jso.getInt("sellerState");
									approvalOpinion = jso.getString("approvalOpinion");
									System.out.println("approvalfail..................");
									url = ("http://" + ip
											+ ":8080/sellerSystem/approvalfail?sellerId="
											+ sellerId + "&approvalOpinion=" + approvalOpinion);
									System.out.println(url);
								} else if (recMessage.equals("complaintinfo")) {
									System.out
											.println("complaintinfo.................................");
									url = ("http://" + ip + ":8080/sellerSystem/complaintinfo");
									System.out.println(url);
								} else if (recMessage.equals("handlecomplaint")) {
									System.out
											.println("handlecomplaint.................................");
									complaintInfoId = jso.getInt("complaintInfoId");
									complaintStatu = jso.getInt("complaintStatu");
									complaintFeedback = jso.getString("complaintFeedback");
									url = ("http://"
											+ ip
											+ ":8080/sellerSystem/handlecomplaint?complaintInfoId="
											+ complaintInfoId + "&complaintStatu="
											+ complaintStatu + "&complaintFeedback=" + complaintFeedback);
									System.out.println(url);
								} else if (recMessage.equals("billbyday")) {
									System.out.println("billbyday..................");
									url = ("http://" + ip + ":8080/sellerSystem/billbyday");
									System.out.println(url);
								} else if (recMessage.equals("billbymonth")) {
									System.out.println("billbymonth..................");
									url = ("http://" + ip + ":8080/sellerSystem/billbymonth");
									System.out.println(url);
								} else if (recMessage.equals("billbyyear")) {
									System.out.println("billbyyear..................");
									url = ("http://" + ip + ":8080/sellerSystem/billbyyear");
									System.out.println(url);
								} else if (recMessage.equals("billbyid_day")) {
									sellerName = jso.getString("sellerName");
									System.out.println("billbyid_day..................");
									url = ("http://" + ip
											+ ":8080/sellerSystem/billbyid_day?sellerName=" + sellerName);
									System.out.println(url);

								} else if (recMessage.equals("billbyid_month")) {
									sellerName = jso.getString("sellerName");
									System.out.println("billbyid_month..................");
									url = ("http://"
											+ ip
											+ ":8080/sellerSystem/billbyid_month?sellerName=" + sellerName);
									System.out.println(url);

								} else if (recMessage.equals("billbyid_year")) {
									sellerName = jso.getString("sellerName");
									System.out.println("billbyid_year..................");
									url = ("http://"
											+ ip
											+ ":8080/sellerSystem/billbyid_year?sellerName=" + sellerName);
									System.out.println(url);

								}
								JSONObject jso1 = new JSONObject();
								jso1.put("url", url);
								TextMessage msg1 = sen.createTextMessage(jso1.toString());
								producer.send(msg1);
								System.out.println(msg1);
								producer.close();

							} catch (Exception e) {
								// TODO Auto-generated catch block
							}
						}
					});

					new Scanner(System.in).nextLine();
					consumer.close();
					sen.close();
					con.close();
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}, 1000 * 2);
	}

}
